from flask import current_app, redirect, url_for, jsonify
from flask import g
from flask import render_template, request
from flask import session
from info.models import User, News
from info.utils.response_code import RET
from . import admin_bp
from info.utils.common import get_user_info
from info import constants
import time
from datetime import datetime
from datetime import timedelta


# 127.0.0.1:5000/admin/news_review_detail?news_id=1
# 127.0.0.1:5000/admin/news_review_detail/news_id=1
@admin_bp.route("/news_review_detail", methods=["POST", "GET"])
@get_user_info
def news_review_detail():
    """新闻审核详情页面接口"""
    if request.method == "GET":
        # 获取参数
        news_id = request.args.get("news_id")

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_review_detail.html", data={"errmsg": "参数错误"})
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template("admin/news_review_detail.html", data={"errmsg": "数据库查询异常"})

        data = {
            "news": news.to_dict()
        }

        return render_template("admin/news_review_detail.html", data=data)

    # POST请求处理审核通过或者不通过

    # 1.获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")
    # 2.校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺失参数")
    if action not in ["accept", "reject"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数不符合")

    # 3.逻辑处理
    # 3.1 查询新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询异常")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻对象为空")
    # 3.2修改新闻对象中的审核状态
    if action == "reject":
        # 审核不通过
        # 获取拒绝原因
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.NODATA, errmsg="拒绝原因不能为空")
        # 修改状态为审核不通过
        news.status = -1
        news.reason = reason
    else:
        #审核通过
        news.status = 0
    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="OK")







# /news_review?p=1
@admin_bp.route("/news_review")
@get_user_info
def news_review():
    """新闻审核接口"""
    # 获取页码参数
    page = request.args.get("p", 1)
    # 校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 数据查询
    news_list = []
    current_page = 1
    total_page = 1

    try:
        paginate = News.query.filter(News.status != 0) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_review_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_review.html', data=context)


# /user_list?page=1
@admin_bp.route("/user_list")
@get_user_info
def user_list():
    """用户列表接口"""
    # 获取参数
    page = request.args.get("page", 1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        return render_template("admin/user_list.html", errmsg="参数类型错误")

    total_page = 0
    current_page = 0
    user_list = []

    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,
                                                                                                       constants.OTHER_NEWS_PAGE_MAX_COUNT,
                                                                                                       False)
        total_page = paginate.pages
        current_page = paginate.page
        user_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/user_list.html", errmsg="数据库查询用户数据异常")

    user_dict_list = []
    for user in user_list:
        user_dict_list.append(user.to_admin_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "users": user_dict_list
    }

    return render_template("admin/user_list.html", data=data)


@admin_bp.route("/user_count", methods=["GET", "POST"])
@get_user_info
def user_count():
    """后台管理页用户统计页数据模板展示"""

    # 1.用户总数查询
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 2.用户月新增数查询
    # 获取到本地电脑的年月日
    """
    time.struct_time(tm_year=2018, tm_mon=7, tm_mday=2, tm_hour=10, tm_min=52, tm_sec=42, tm_wday=0, tm_yday=183, tm_isdst=0)
    """

    t = time.localtime()
    date = datetime.strptime("%d-%02d-01" % (t.tm_year, t.tm_mon), "%Y-%m-%d")
    mon_count = 0
    try:
        mon_count = User.query.filter(User.is_admin == False, User.create_time > date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 1.用户日新增数查询
    day_count = 0
    t = time.localtime()
    date = datetime.strptime("%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 折线图用户一个月的每天活跃量数据
    today_date = datetime.strptime("%d-%02d-%02d" % (t.tm_year, t.tm_mon, t.tm_mday), "%Y-%m-%d")

    # 用户活跃量
    count = 0
    active_count = []
    active_date = []

    for i in range(0, 31):
        begin_date = today_date - timedelta(days=i)
        end_date = begin_date + timedelta(days=i + 1)
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)
        active_date.append(begin_date.strftime("%Y-%m-%d"))
    # 数据翻转
    active_date.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_count": active_count,
        "active_date": active_date

    }
    return render_template("admin/user_count.html", data=data)


@admin_bp.route("/index", methods=["GET", "POST"])
@get_user_info
def admin_index():
    """后台管理首页"""
    user = g.user
    return render_template("admin/index.html", data=user.to_dict())


@admin_bp.route("/login", methods=["GET", "POST"])
def admin_login():
    """管理员登录接口"""
    if request.method == "GET":
        # 如果管理员用户已经登录，直接引导到admin首页
        user_id = session.get("user_id")
        is_admin = session.get("is_admin")
        if user_id and is_admin:
            return redirect(url_for("admin.admin_index"))

        return render_template("admin/login.html")

    # 获取参数
    username = request.form.get("username")
    password = request.form.get("password")
    # 参数校验
    if not all([username, password]):
        return render_template("admin/login.html", errmsg="账号密码错误")
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据库查询异常")

    if not user:
        return render_template("admin/login.html", errmsg="用户数据不存在")

    # 密码校验操作
    if not user.check_password(password):
        return render_template("admin/login.html", errmsg="密码错误")

    # 使用session保存管理员登录信息
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.mobile
    session["is_admin"] = user.is_admin

    # 跳转到管理首页
    return redirect(url_for("admin.admin_index"))
